<template>
  <div class="login-container">
    <a-card title="用户登录" class="login-card">
      <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          @finish="handleSubmit"
          layout="vertical"
      >
        <a-form-item label="用户名" name="loginName">
          <a-input v-model:value="formState.loginName" placeholder="请输入用户名">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item label="密码" name="password">
          <a-input-password
              v-model:value="formState.password"
              placeholder="请输入密码"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <a-button
              type="primary"
              html-type="submit"
              block
              :loading="loading"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import {useRouter} from 'vue-router';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { login } from '@/api/login';
const formRef = ref();
const loading = ref(false);
const router = useRouter();
const formState = reactive({
  loginName: '',
  password: ''
});

const rules = {
  loginName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
};

const handleSubmit = async () => {
  try {
    loading.value = true;
    // 这里添加实际登录逻辑
    const res = await login({
      loginName: formState.loginName,
      password: formState.password
    })

    if(res.code === 200){
      // 登录成功
      console.log(res);
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('admin', JSON.stringify(res.data))
      message.success('登录成功');
      // 跳转到首页
      await router.push('/layout');
    }else{
      message.error('登录失败')
    }
  } catch (error) {
    message.error(error.message || '登录失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-image: url('@/assets/vehicle.png');
}

.login-card {
  width: 100%;
  max-width: 400px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.ant-card-head-title) {
  text-align: center;
  font-size: 1.5rem;
}
</style>
